document.addEventListener('DOMContentLoaded', () => {
    // 等待资源加载完成后再初始化游戏
    assets.loadImages(() => {
        const canvas = document.getElementById('game-canvas');
        const ctx = canvas.getContext('2d');
        const livesDisplay = document.getElementById('lives');
        const scoreDisplay = document.getElementById('score');
        const enemiesDisplay = document.getElementById('enemies');
        const gameOverDisplay = document.getElementById('game-over');
        const finalScoreDisplay = document.getElementById('final-score');
        // 初始化按钮事件
        const pauseBtn = document.getElementById('pause-btn');
        const continueBtn = document.getElementById('continue-btn');
        const restartBtn = document.getElementById('restart-btn');
        
        // 游戏状态
        const state = {
            gameOver: false,
            score: 0,
            lives: 3,
            enemiesLeft: 5,
            level: 1,
            player: null,
            enemies: [],
            bullets: [],
            walls: [],
            powerUps: [],
            lastEnemySpawnTime: 0,
            enemySpawnInterval: 3000, // 3秒
            keys: {}
        };
        
        // 游戏对象
        class Tank {
            constructor(x, y, width, height, color, speed, direction) {
                this.x = x;
                this.y = y;
                this.width = width;
                this.height = height;
                this.color = color;
                this.speed = speed;
                this.direction = direction; // 0: 上, 1: 右, 2: 下, 3: 左
                this.health = 1;
                this.cooldown = 0;
                this.maxCooldown = 20;
                this.isPlayer = false;
                
                // 根据颜色选择对应的坦克和炮管图片
                switch(color) {
                    case '#4CAF50':
                        this.tankImage = assets.getImage('tankGreen');
                        this.barrelImage = assets.getImage('barrelGreen');
                        this.bulletImage = assets.getImage('bulletGreen');
                        break;
                    case '#F44336':
                        this.tankImage = assets.getImage('tankRed');
                        this.barrelImage = assets.getImage('barrelRed');
                        this.bulletImage = assets.getImage('bulletRed');
                        break;
                    default:
                        this.tankImage = assets.getImage('tankBeige');
                        this.barrelImage = assets.getImage('barrelBeige');
                        this.bulletImage = assets.getImage('bulletBeige');
                }
            }
            
            update() {
                if (this.cooldown > 0) {
                    this.cooldown--;
                }
                
                // 根据方向移动
                switch (this.direction) {
                    case 0: // 上
                        this.y -= this.speed;
                        break;
                    case 1: // 右
                        this.x += this.speed;
                        break;
                    case 2: // 下
                        this.y += this.speed;
                        break;
                    case 3: // 左
                        this.x -= this.speed;
                        break;
                }
                
                // 边界检查
                if (this.x < 0) this.x = 0;
                if (this.y < 0) this.y = 0;
                if (this.x > canvas.width - this.width) this.x = canvas.width - this.width;
                if (this.y > canvas.height - this.height) this.y = canvas.height - this.height;
            }
            
            draw() {
                ctx.save();
                
                // 移动到坦克中心点
                ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
                
                // 根据方向旋转
                ctx.rotate(this.direction * Math.PI / 2);
                
                // 绘制坦克主体（从中心点偏移）
                ctx.drawImage(this.tankImage, -this.width / 2, -this.height / 2, this.width, this.height);
                
                // 绘制炮管（从中心点向前延伸）
                ctx.drawImage(this.barrelImage, -2, -20, 4, 20);
                
                ctx.restore();
            }
            
            shoot() {
                if (this.cooldown <= 0) {
                    let bulletX, bulletY;
                    
                    switch (this.direction) {
                        case 0: // 上
                            bulletX = this.x + this.width / 2 - 2;
                            bulletY = this.y - 5;
                            break;
                        case 1: // 右
                            bulletX = this.x + this.width + 5;
                            bulletY = this.y + this.height / 2 - 2;
                            break;
                        case 2: // 下
                            bulletX = this.x + this.width / 2 - 2;
                            bulletY = this.y + this.height + 5;
                            break;
                        case 3: // 左
                            bulletX = this.x - 5;
                            bulletY = this.y + this.height / 2 - 2;
                            break;
                    }
                    
                    const bullet = new Bullet(bulletX, bulletY, this.direction, this.isPlayer);
                    state.bullets.push(bullet);
                    this.cooldown = this.maxCooldown;
                    return true;
                }
                return false;
            }
            
            checkCollision(object) {
                return (
                    this.x < object.x + object.width &&
                    this.x + this.width > object.x &&
                    this.y < object.y + object.height &&
                    this.y + this.height > object.y
                );
            }
        }
        
        class Bullet {
        constructor(x, y, direction, isPlayerBullet) {
            this.x = x;
            this.y = y;
            this.width = 8;
            this.height = 8;
            this.speed = 5;
            this.direction = direction;
            this.isPlayerBullet = isPlayerBullet;
            this.active = true;
            
            // 根据发射者选择子弹图片
            this.bulletImage = isPlayerBullet ? 
                assets.getImage('bulletGreen') : 
                assets.getImage('bulletRed');
        }
            // constructor(x, y, direction, isPlayerBullet) {
            //     this.x = x;
            //     this.y = y;
            //     this.width = 4;
            //     this.height = 4;
            //     this.speed = 5;
            //     this.direction = direction;
            //     this.isPlayerBullet = isPlayerBullet;
            //     this.active = true;
            // }
            
            update() {
                switch (this.direction) {
                    case 0: // 上
                        this.y -= this.speed;
                        break;
                    case 1: // 右
                        this.x += this.speed;
                        break;
                    case 2: // 下
                        this.y += this.speed;
                        break;
                    case 3: // 左
                        this.x -= this.speed;
                        break;
                }
                
                // 检查是否超出屏幕
                if (
                    this.x < 0 || 
                    this.x > canvas.width || 
                    this.y < 0 || 
                    this.y > canvas.height
                ) {
                    this.active = false;
                }
            }
            
            draw() {
                ctx.save();
                ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
                ctx.rotate(this.direction * Math.PI / 2);
                ctx.translate(-(this.x + this.width / 2), -(this.y + this.height / 2));
                ctx.drawImage(this.bulletImage, this.x, this.y, this.width, this.height);
                ctx.restore();
            }
            
            checkCollision(object) {
                return (
                    this.x < object.x + object.width &&
                    this.x + this.width > object.x &&
                    this.y < object.y + object.height &&
                    this.y + this.height > object.y
                );
            }
        }
        
        class Wall {
            constructor(x, y, width, height, breakable) {
                this.x = x;
                this.y = y;
                this.width = width;
                this.height = height;
                this.breakable = breakable;
                this.health = breakable ? 2 : Infinity;
                
                // 选择墙壁图片
                this.wallImage = breakable ? 
                    assets.getImage('sandbagBeige') : 
                    assets.getImage('barrelGrey');
            }
            // constructor(x, y, width, height, breakable) {
            //     this.x = x;
            //     this.y = y;
            //     this.width = width;
            //     this.height = height;
            //     this.breakable = breakable;
            //     this.health = breakable ? 2 : Infinity;
            // }
            
            draw() {
                ctx.drawImage(this.wallImage, this.x, this.y, this.width, this.height);
                
                if (this.breakable && this.health === 1) {
                    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
                    ctx.fillRect(this.x, this.y, this.width, this.height);
                }
            }
        }
        
        // 初始化游戏
        function initGame() {
            state.gameOver = false;
            state.score = 0;
            state.lives = 3;
            state.enemiesLeft = 5 + state.level * 2;
            state.player = null;
            state.enemies = [];
            state.bullets = [];
            state.walls = [];
            state.powerUps = [];
            state.lastEnemySpawnTime = 0;
            
            // 创建玩家坦克
            state.player = new Tank(
                // canvas.width / 2 - 15,
                // canvas.height - 40,
                210, 540,
                30, 30,
                '#4CAF50',
                3,
                0
            );
            state.player.isPlayer = true;
            console.log('state.player', state.player);

            // 创建墙壁
            createWalls();
            
            // 更新显示
            updateDisplay();
            
            // 隐藏游戏结束界面
            gameOverDisplay.style.display = 'none';
            
            // 开始游戏循环
            if (!state.gameLoop) {
                state.gameLoop = setInterval(gameLoop, 1000 / 60);
            }
        }
        
        function createWalls() {
            // 创建不可破坏的边界墙
            for (let i = 0; i < canvas.width; i += 20) {
                // 上边界
                state.walls.push(new Wall(i, 0, 20, 20, false));
                // 下边界
                state.walls.push(new Wall(i, canvas.height - 20, 20, 20, false));
            }
            
            for (let i = 20; i < canvas.height - 20; i += 20) {
                // 左边界
                state.walls.push(new Wall(0, i, 20, 20, false));
                // 右边界
                state.walls.push(new Wall(canvas.width - 20, i, 20, 20, false));
            }
            
            // 创建一些可破坏的墙
            for (let i = 0; i < 10; i++) {
                const x = Math.floor(Math.random() * (canvas.width - 60) / 20) * 20 + 20;
                const y = Math.floor(Math.random() * (canvas.height - 60) / 20) * 20 + 20;
                state.walls.push(new Wall(x, y, 20, 20, true));
            }
            
            // 保护玩家基地的墙
            const baseX = canvas.width / 2 - 30;
            const baseY = canvas.height - 40;
            state.walls.push(new Wall(baseX - 20, baseY, 20, 20, false));
            state.walls.push(new Wall(baseX + 30, baseY, 20, 20, false));
        }
        
        function spawnEnemy() {
            const x = Math.floor(Math.random() * (canvas.width - 60) / 20) * 20 + 20;
            const y = 20;
            const direction = 2; // 向下
            
            const enemy = new Tank(
                x, y,
                30, 30,
                '#F44336',
                2,
                direction
            );
            console.log('enemy', enemy);
            
            state.enemies.push(enemy);
        }
        
        function updateEnemies() {
            // 随机移动和射击
            state.enemies.forEach(enemy => {
                // 随机改变方向
                if (Math.random() < 0.02) {
                    enemy.direction = Math.floor(Math.random() * 4);
                }
                
                // 随机射击
                if (Math.random() < 0.02) {
                    enemy.shoot();
                }
                
                enemy.update();
                
                // 检查与墙壁的碰撞
                state.walls.forEach(wall => {
                    if (enemy.checkCollision(wall)) {
                        // 反弹
                        switch (enemy.direction) {
                            case 0: enemy.y = wall.y + wall.height; break;
                            case 1: enemy.x = wall.x - enemy.width; break;
                            case 2: enemy.y = wall.y - enemy.height; break;
                            case 3: enemy.x = wall.x + wall.width; break;
                        }
                        
                        // 改变方向
                        enemy.direction = Math.floor(Math.random() * 4);
                    }
                });
            });
        }
        
        function updateBullets() {
            state.bullets.forEach((bullet, index) => {
                if (!bullet.active) {
                    state.bullets.splice(index, 1);
                    return;
                }
                
                bullet.update();
                
                // 检查子弹与墙壁的碰撞
                state.walls.forEach((wall, wallIndex) => {
                    if (bullet.checkCollision(wall)) {
                        bullet.active = false;
                        
                        if (wall.breakable) {
                            wall.health--;
                            if (wall.health <= 0) {
                                state.walls.splice(wallIndex, 1);
                            }
                        }
                    }
                });
                
                // 检查子弹与坦克的碰撞
                if (bullet.isPlayerBullet) {
                    // 玩家子弹检查敌人碰撞
                    state.enemies.forEach((enemy, enemyIndex) => {
                        if (bullet.checkCollision(enemy)) {
                            bullet.active = false;
                            state.enemies.splice(enemyIndex, 1);
                            state.score += 100;
                            state.enemiesLeft--;
                            updateDisplay();
                        }
                    });
                } else {
                    // 敌人子弹检查玩家碰撞
                    if (bullet.checkCollision(state.player)) {
                        bullet.active = false;
                        state.lives--;
                        updateDisplay();
                        
                        if (state.lives <= 0) {
                            gameOver();
                        } else {
                            // 重置玩家位置
                            state.player.x = canvas.width / 2 - 15;
                            state.player.y = canvas.height - 40;
                            state.player.direction = 0;
                        }
                    }
                }
            });
        }
        
        function updateDisplay() {
            livesDisplay.textContent = state.lives;
            scoreDisplay.textContent = state.score;
            enemiesDisplay.textContent = state.enemiesLeft;
        }
        
        function gameOver() {
            state.gameOver = true;
            clearInterval(state.gameLoop);
            state.gameLoop = null;
            
            finalScoreDisplay.textContent = state.score;
            gameOverDisplay.style.display = 'flex';
        }
        
        function checkLevelComplete() {
            if (state.enemiesLeft <= 0 && state.enemies.length === 0) {
                state.level++;
                initGame();
            }
        }
        
        // 游戏主循环
        function gameLoop() {
            if (!state.paused) {
                // 清除画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制背景
                const grassPattern = ctx.createPattern(assets.getImage('grass'), 'repeat');
                ctx.fillStyle = grassPattern;
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                // 更新玩家
                if (state.player) {
                    // 处理键盘输入
                    if (state.keys['ArrowUp']) {
                        state.player.direction = 0;
                        state.player.update();
                    }
                    if (state.keys['ArrowRight']) {
                        state.player.direction = 1;
                        state.player.update();
                    }
                    if (state.keys['ArrowDown']) {
                        state.player.direction = 2;
                        state.player.update();
                    }
                    if (state.keys['ArrowLeft']) {
                        state.player.direction = 3;
                        state.player.update();
                    }
                    if (state.keys[' ']) {
                        state.player.shoot();
                    }
                    
                    // 检查玩家与墙壁的碰撞
                    state.walls.forEach(wall => {
                        if (state.player.checkCollision(wall)) {
                            switch (state.player.direction) {
                                case 0: state.player.y = wall.y + wall.height; break;
                                case 1: state.player.x = wall.x - state.player.width; break;
                                case 2: state.player.y = wall.y - state.player.height; break;
                                case 3: state.player.x = wall.x + wall.width; break;
                            }
                        }
                    });
                    
                    state.player.draw();
                }
                
                // 生成敌人
                const now = Date.now();
                if (
                    state.enemies.length < 3 && 
                    state.enemiesLeft > 0 && 
                    now - state.lastEnemySpawnTime > state.enemySpawnInterval
                ) {
                    spawnEnemy();
                    state.lastEnemySpawnTime = now;
                }
                
                // 更新敌人
                updateEnemies();
                
                // 更新子弹
                updateBullets();
                
                // 绘制墙壁
                state.walls.forEach(wall => wall.draw());
                
                // 绘制敌人
                state.enemies.forEach(enemy => enemy.draw());
                
                // 绘制子弹
                state.bullets.forEach(bullet => bullet.draw());
                
                // 检查关卡是否完成
                checkLevelComplete();
            }
        }
        
        // 键盘事件监听
        window.addEventListener('keydown', (e) => {
            state.keys[e.key] = true;
        });
        
        window.addEventListener('keyup', (e) => {
            state.keys[e.key] = false;
        });
        
        // 重新开始按钮
        function restartGame() {
            state.paused = false;
            state.level = 1;
            initGame();
            pauseBtn.disabled = false;
            continueBtn.disabled = true;
        }
        
        // 暂停游戏
        function pauseGame() {
            state.paused = true;
        }
        
        // 继续游戏
        function continueGame() {
            state.paused = false;
        }

        function initButtons() {
            pauseBtn.addEventListener('click', pauseGame);
            continueBtn.addEventListener('click', continueGame);
            restartBtn.addEventListener('click', restartGame);
        }
        
        // 在游戏初始化时调用按钮初始化
        initButtons();
        
        // 初始化游戏
        initGame();
    });
});